package com.xsprite.managesys.servlet.gm;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.mina.core.session.IoSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.game.GMClientServer;
import com.game.gm.config.GMComm;
import com.game.gm.handler.ResGMmsgHandler;
import com.game.gm.load.GMCommLoad;
import com.game.gm.manager.GMManager;
import com.xsprite.managesys.bean.GoodsType;
import com.xsprite.managesys.servlet.BaseServlet;
import com.zhangzhang.util.Util;

/**
 * Servlet implementation class SendEmailServlet
 */
public class SendEmailServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		try {
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(queryParam("paras"));
			if (checkParas(jsonObj)){
				ResGMmsgHandler handler = new ResGMmsgHandler();
				handler.setUserid(getReq().getSession().getAttribute("userid").toString());
				handler.setGmNo(1);
				sendEmail(jsonObj, handler);
				while(!handler.isFinish()){
					Thread.sleep(500);
				}
			}
		} catch (Exception ex) {
			getResp().getWriter().print(ex.getMessage());
			ex.printStackTrace();
		}
	}

	private void sendEmail(JSONObject jsonObject, ResGMmsgHandler handler) throws IOException {
		String mailInfos = makeMailInfos(jsonObject);
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		JSONObject serverObj = (JSONObject) serversArray.get(0);
		String tag = serverObj.getString("tag");
		sendEmailToPlayers(jsonObject, mailInfos, tag, handler);
	}

	private void sendEmailToPlayers(JSONObject jsonObject, String mailInfos, String tag, ResGMmsgHandler handler) throws IOException {
		String playerNames = jsonObject.getString("playerName");
		String[] roles = playerNames.split(",");
		IoSession session = GMClientServer.getInstance().createSession(tag, getResp().getWriter(), handler);
		for (String roleName : roles) {
			StringBuffer gmcommbuff = new StringBuffer();
			GMComm gmcomm = (GMComm) GMCommLoad.getInstance().getGmComms().get(Integer.valueOf(1));
			gmcommbuff.append(gmcomm.getGmComm());
			gmcommbuff.append(" ");
			gmcommbuff.append(roleName);
			gmcommbuff.append(" ");
			gmcommbuff.append(mailInfos);
			GMManager.getInstance().sendGMmsg(session, gmcommbuff.toString());
		}
	}

	private String makeMailInfos(JSONObject jsonObject){
		StringBuffer gmcommbuf = new StringBuffer();
		String emailTitle = jsonObject.getString("emailTitle");
		gmcommbuf.append(emailTitle);
		gmcommbuf.append(" ");
		String emailContent = jsonObject.getString("emailContent");
		gmcommbuf.append(emailContent);
		gmcommbuf.append(" ");

		StringBuffer goodsBuff = new StringBuffer();
		for (int i = 0; i < 5; i++) {
			GoodsType goodsType = GoodsType.getGoodsTypeByValue(jsonObject.getInteger("goodsType" + i));
			if (goodsType == GoodsType.NOTYPE) {
				continue;
			}
			goodsBuff.append(goodsType.getValue() + ",");
			String goodsIdStr = jsonObject.getString("goodsId" + i);
			goodsBuff.append(goodsIdStr + ",");
			String goodsAmountStr = jsonObject.getString("goodsAmount" + i);
			goodsBuff.append(goodsAmountStr + ",");
		}
		if (goodsBuff.length() <= 0) {
			gmcommbuf.append("0");
		} else {
			goodsBuff.delete(goodsBuff.length() - 1, goodsBuff.length());
			gmcommbuf.append(goodsBuff);
		}
		return gmcommbuf.toString();
	}
	
	private boolean checkParas(JSONObject jsonObject) throws IOException {
		JSONArray serversArray = jsonObject.getJSONArray("servers");
		if(serversArray.size() < 1){
			getResp().getWriter().print("服务器不能为空");
			return false;
		}
		String playerName = jsonObject.getString("playerName");
		if (playerName == null || playerName.equals("") || playerName.equals(" ") || playerName.equals("	")) {
			getResp().getWriter().print("角色名不能为空");
			return false;
		}
		String emailTitle = jsonObject.getString("emailTitle");
		if (emailTitle == null || emailTitle.equals("")) {
			getResp().getWriter().print("标题不能为空");
			return false;
		}
		String emailContent = jsonObject.getString("emailContent");
		if (emailContent == null || emailContent.equals("")) {
			getResp().getWriter().print("内容不能为空");
			return false;
		}
		return checkGoods(jsonObject);
	}

	private boolean checkGoods(JSONObject jsonObject) throws IOException {
		for (int i = 0; i < 5; i++) {
			int goodsTypeValue = jsonObject.getInteger("goodsType" + i);
			GoodsType goodsType = GoodsType.getGoodsTypeByValue(goodsTypeValue);
			if (goodsType != GoodsType.NOTYPE) {
				String goodsIdStr = jsonObject.getString("goodsId" + i);
				if (!Util.isNumeric(goodsIdStr)) {
					getResp().getWriter().print("物品id必须为数字");
					return false;
				}
				String goodsAmountStr = jsonObject.getString("goodsAmount" + i);
				if (!Util.isNumeric(goodsAmountStr)) {
					getResp().getWriter().print("物品数量必须为数字");
					return false;
				}
			}
		}
		return true;
	}
}
